<template>
  <svg class="connection" :style="connectionStyle">
    <path :d="pathData" :stroke="connection.selected ? '#4299e1' : '#718096'" :class="connection.selected ? 'line-selected' : 'line-normal'"
      :stroke-width="connection.selected ? 3 : 2" fill="none" @mousedown.stop="handleMouseDown" />
  </svg>
</template>

<script setup>
import { computed, inject } from 'vue';

// Props
const props = defineProps({
  connection: {
    type: Object,
    required: true
  },
  sourceNode: {
    type: Object,
    required: true
  },
  targetNode: {
    type: Object,
    required: true
  }
});

// Emits
const emit = defineEmits(['select']);

// Injected values
const scale = inject('scale', () => 1);
const translateX = inject('translateX', () => 0);
const translateY = inject('translateY', () => 0);

// Computed properties
const startPoint = computed(() => {
  // 使用源节点的输出端点绝对坐标
  if (props.sourceNode && props.sourceNode.outputs && 
      props.sourceNode.outputs[props.connection.sourcePortIndex]) {
    return props.sourceNode.outputs[props.connection.sourcePortIndex];
  }
  // 兼容处理：如果没有计算好的坐标，则使用原来的计算方式
  const port = props.sourceNode.outputs[props.connection.sourcePortIndex];
  return {
    x: props.sourceNode.x + port.x,
    y: props.sourceNode.y + port.y
  };
});

const endPoint = computed(() => {
  // 使用目标节点的输入端点绝对坐标
  if (props.targetNode && props.targetNode.inputs && 
      props.targetNode.inputs[props.connection.targetPortIndex]) {
    return props.targetNode.inputs[props.connection.targetPortIndex];
  }
  // 兼容处理：如果没有计算好的坐标，则使用原来的计算方式
  const port = props.targetNode.inputs[props.connection.targetPortIndex];
  return {
    x: props.targetNode.x + port.x,
    y: props.targetNode.y + port.y
  };
});

const pathData = computed(() => {
  if (!props.sourceNode || !props.targetNode) {
    return '';
  }
  console.log(startPoint.value);
  console.log(endPoint.value);
  const { x: startX, y: startY } = startPoint.value;
  const { x: endX, y: endY } = endPoint.value;
  const midX = (startX + endX) / 2;
  return `M${startX},${startY} C${midX},${startY} ${midX},${endY} ${endX},${endY}`;
});

const connectionStyle = computed(() => ({
  position: 'absolute',
  top: 0,
  left: 0,
  width: '100%',
  height: '100%',
  zIndex: 1
}));

// Methods
const handleMouseDown = () => {
  emit('select', props.connection);
};
</script>

<style>
@import '../assets/styles/connection.css';
</style>